package clock.socoolby.com.clock.fragment.alter;

import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import java.util.Date;

import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.state.ClockStateMachine;
import clock.socoolby.com.clock.utils.Player;
import clock.socoolby.com.clock.viewmodel.AlterViewModel;
import clock.socoolby.com.clock.viewmodel.GlobalViewModel;
import clock.socoolby.com.clock.viewmodel.ViewModelFactory;

public abstract class AbstractAlterFragment extends Fragment {
    GlobalViewModel globalViewModel;
    AlterViewModel alterViewModel;

    ClockStateMachine clockStateMachine;

    int view_id;

    public AbstractAlterFragment( int view_id) {
        this.view_id=view_id;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        globalViewModel= ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(GlobalViewModel.class);
        alterViewModel=ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(AlterViewModel.class);
        clockStateMachine=globalViewModel.getClockStateMachine();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(view_id, container, false);
        bindView(view);
        bindViewModel();
        return view;
    }

    abstract void bindView(View rootView);


    abstract void bindViewModel();


    protected void endAlter(Date delayDate){
        clockStateMachine.stopAlter(delayDate);
        Player.getInstance().resert();
    }


    protected void playHandUpMusic(){
        Uri musicUri=alterViewModel.getHandUpMusic().getValue();
        if(musicUri==null) {
            Player.getInstance().playHandUp(ClockApplication.getContext());
            return;
        }

        Player.getInstance().playRing(ClockApplication.getContext(),musicUri);
    }

}
